/* eslint-disable no-shadow */
import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { View, Input, ScrollView } from '@tarojs/components'
import { AtButton } from 'taro-ui'
import { Fragment } from 'react'
import StoreListView from '@/components/StoreListView'
import classnames from 'classnames'
import OpenLocation from '@/components/OpenLocation'
import map from '@/utils/map'
import { connect } from 'react-redux'
import { updateStore, initLocation } from '@/store/location/action'
import { oftenStore, nearStore as nearStoreApi, allStore } from '@/api'
import { getAreaInfo } from '@/api/platform'
import './index.scss'
import { debounce } from '@/utils'

interface State {
  address: any
  tabIndex: number
  store: IStore | null
  loadLocation: boolean
  otfenStore: IStore[] | null
  commonlyUsed: []
  nearStore: IStore[] | null
  reload: boolean
  keyWordStore: IStore[]
  allStoreList: IStore[],
  canLoadNearStore: Boolean,
	keyword:string
	selectArea:object
}

@connect<any>(({ location, user }) => ({ location, user }), _dispatch => ({
  dispatchStore(params) {
    return _dispatch(updateStore(params))
  },
  dispatchLocation(params) {
    return _dispatch(initLocation(params))
  }
}))
export default class Index extends Component<any> {
  $instance = getCurrentInstance();
	protected __data__: any
  constructor (props) {
    super(props)
    this.state = {
      address: null,
      tabIndex: 2,
      store: null,
      loadLocation: false,
      otfenStore: null,
      commonlyUsed: [],// 常用门店
      nearStore: null,// 附近门店
      reload: false,
      keyWordStore: [],
      allStoreList: [],
      canLoadNearStore: true,
			keyword:'',
			selectArea:{},
    }
		this.__data__ = process.env.TARO_ENV === 'weapp' ? '__data__' : 'data'
  }
  state: State

  UNSAFE_componentWillMount() {
    console.log('UNSAFE_componentWillMount')
  }
  async componentDidMount() {
    const { address='' } = this.props.location
    const { tabIndex } = this.$instance.router.params
    let params = {}
    if (address) {
      const { lat: latitude, lng: longitude } = address.location
      params = {
        location: { latitude, longitude }
      }
    }
    await this.getLocation(params)
    this.getNearStore('tab')
  }
  UNSAFE_componentWillReceiveProps(nextProps, nextContext) {
    const { address, canLoadNearStore } = this.state
    const { user } = this.props
    const propsLocation = nextProps.location.address
    console.log('执行-------UNSAFE_componentWillReceiveProps', propsLocation)
    if (propsLocation) {
      if (address) {
        if (propsLocation.address !== address.address) {
          this.setState({
            location: propsLocation,
            address: propsLocation
          }, () => {
            if (user.userInfo.accessId) {
              this.getOtfenStore(nextProps.location)
            }
          })
        }
      } else {
        const { method } = this.$instance.router.params
        if (method) {
          if (method === 'vendorStore') {
            this.getAllStore(nextProps.location)
            Taro.setNavigationBarTitle({
              title: '门店'
            })
          }
          return
        } else {
          this.setState({
            location: propsLocation,
            address: propsLocation
          }, () => {
            this.getNearStore('tab')
          })
        }
      }
    }
  }
  componentWillUnmount() { }
  async componentDidShow() {
		let city = Taro.getStorageSync('CURRENT_LOCATION_INFO') || {}
		let IS_RELOAD_STORE_INFO = Taro.getStorageSync('IS_RELOAD_STORE_INFO') || 0
		let pages = Taro.getCurrentPages();
		let currentPage = pages[pages.length - 1]; // 获取当前页面
		let {selectArea} = this.state
		if (selectArea && currentPage[this.__data__].selectArea) { // 获取值
			this.setState({ selectArea: currentPage[this.__data__].selectArea})
		}
		console.log('pages-------pages',pages)
		console.log('currentPage',currentPage)
		this.setState({
			keyword:'',
			keyWordStore:[],
		},()=>{
			this.nearStorePage = 1
			this.setState({
				commonlyUsed:[],
				nearStore:[],
			},()=>{
				console.log('currentPage',currentPage)
				if( IS_RELOAD_STORE_INFO == 1 && currentPage[this.__data__].selectArea && currentPage[this.__data__].selectArea.adCode){
					console.log('执行1')
					this.getNearStore('init',true)
				}else{
					console.log('执行2')
					this.getFun()
				}
			})
		})

  }
  componentDidHide() {
		console.log('出去执行。。')
		this.setState({ selectArea: {}})
	}
  componentDidCatchError() { }
  componentDidNotFound() { }

  // 当前位置信息
  async getLocation(params?) {
		console.log('params---',params)
    const reverseGeocoder: any = await map.reverseGeocoder(params)
    if (reverseGeocoder) {
      const { dispatchLocation } = this.props
      const address = {
        city: reverseGeocoder.ad_info.city,
        address: reverseGeocoder.address,
        location: reverseGeocoder.location || {},
        title: reverseGeocoder.formatted_addresses.recommend
      }
      dispatchLocation(address)
      this.setState({
        reload: true,
        address,
        loadLocation: true
      })
    } else {
      this.setState({
        reload: true,
        loadLocation: true
      })
    }
  }

  // 开启定位
  openSetting() {
    Taro.openSetting().then(res => {
      const status = res.authSetting['scope.userLocation']
      if (status) {
        this.setState({
          reload: false
        })
        this.getLocation()
      }
    })
  }

  // 附近门店数据
  getNearStore = (mode?= 'init',currentMode? = false) => {
		let {selectArea} = this.state
    if (process.env.TARO_ENV === 'weapp') { // 微信小程序
      // const { address } = this.props.location
			console.log('微信小程序  this.props', this.props)
      const { nearStore, canLoadNearStore } = this.state
      if (mode === 'tab') {
        //首次点击菜单栏进入会执行 UNSAFE_componentWillReceiveProps 和 componentDidMount，数据重复
        if (nearStore || !canLoadNearStore) {
          return
        } else {
          this.setState({
            canLoadNearStore: false
          })
        }
      }
			let city = Taro.getStorageSync('CURRENT_LOCATION_INFO') || {}
			let current = Taro.getStorageSync('CURRENT_LONGITUDE_LATITUDE') || {}
			console.log('city',city)
			let paramsData = {}
			if(city.adCode){
					paramsData = {
					userLongitude: current && current.longitude,
					userLatitude: current && current.latitude,
					query: {
						page: this.nearStorePage,
						perPage: 10,
						filter:{and:[{cityCode: currentMode ? (selectArea && selectArea.adCode ?selectArea.adCode : '')  : city.adCode || ''}]}
					}
				}
			}else{
				paramsData = {
					userLongitude: current && current.longitude,
					userLatitude: current && current.latitude,
					query: {
						page: this.nearStorePage,
						perPage: 10
					}
				}
			}
      // 如果链接携带分销信息 查询门店时需一起发送
      let { goodsDistributionId } = this.$instance.router.params
      if (goodsDistributionId) {
        paramsData.query.goodsDistributionId = goodsDistributionId
      }
			if(paramsData.userLongitude){
					nearStoreApi(paramsData).then(res => {
						const data = res.data.data
						console.log(data.length)
		const totalPage = Number(res.header['x-pagination-page-count']) || Number(res.header['X-Pagination-Page-Count'])
						if (this.nearStorePage >= totalPage) {
							this.canAddNearStore = false
						}
						let list = []
						let commonlyUsed =  this.state.commonlyUsed || []// 常用门店
						let nearStore = this.state.nearStore || []// 附近门店
						if (nearStore.length > 0) {
							list = [...nearStore, ...data]
						} else {
							list = [...data]
						}
						let nearStore2 = []
						list.map((val) => {
							if (val.commonly && val.commonly == 1) {
								commonlyUsed.push(val)
							} else {
								nearStore2.push(val)
							}
						})
						this.setState({
							commonlyUsed,
							nearStore: nearStore2,
						})
					})
			}
    } else { // 支付宝小程序
      let _this = this
      my.showLoading()
      my.getLocation({
        type: 2,
        async success(res) {
          my.hideLoading()
          let { latitude, longitude } = res
          let location = res
					let city = Taro.getStorageSync('CURRENT_LOCATION_INFO') || {}
					console.log('city',city)
					let paramsData = {}
					if(city.adCode){
						console.log('进来这里了吗')
						 paramsData = {
							userLongitude: longitude,
							userLatitude: latitude,
							query: {
								page: _this.nearStorePage,
								perPage: 10,
								filter:{and:[{cityCode: currentMode ? (selectArea && selectArea.adCode ?selectArea.adCode : '')  : city.adCode || ''}]}
							}
						}
						console.log('paramsData',paramsData)
					}else{
						 paramsData = {
							userLongitude: longitude,
							userLatitude: latitude,
							query: {
								page: _this.nearStorePage,
								perPage: 10,
							}
						}
					}

          // 如果链接携带分销信息 查询门店时需一起发送
          let { goodsDistributionId } = _this.$instance.router.params
          if (goodsDistributionId) {
            paramsData.query.goodsDistributionId = goodsDistributionId
          }
          nearStoreApi(paramsData).then(res => {
            const data = res.data.data
            console.log(data.length)
            const totalPage = Number(res.header['x-pagination-page-count']) || Number(res.header['X-Pagination-Page-Count'])
            if (_this.nearStorePage >= totalPage) {
              _this.canAddNearStore = false
            }
            let list = []
						let commonlyUsed =  _this.state.commonlyUsed || []// 常用门店
            let nearStore = _this.state.nearStore || []// 附近门店
            if (nearStore.length > 0) {
              list = [...nearStore, ...data]
            } else {
              list = [...data]
            }
            let nearStore2 = []
            list.map((val) => {
              if (val.commonly && val.commonly == 1) {
                commonlyUsed.push(val)
              } else {
                nearStore2.push(val)
              }
            })
            _this.setState({
              address: location,
              commonlyUsed,
              nearStore: nearStore2,
            })
          })

        },
        async fail() {
          my.hideLoading()
        }
      })
    }

  }

  // 常用门店数据
  getOtfenStore(params?) {
    const { address } = params || this.state
    const { otfenStore } = this.state
    const newParams = {
      userLongitude: address.location.lng,
      userLatitude: address.location.lat,
      query: {
        page: this.otfenStorePage
      }
    }
    // 如果链接携带分销信息 查询门店时需一起发送
    let { goodsDistributionId } = this.$instance.router.params
    if (goodsDistributionId) {
      newParams.query.goodsDistributionId = goodsDistributionId
    }

    oftenStore(newParams).then(res => {
      const data = res.data.data
      const totalPage = Number(res.header['x-pagination-page-count']) || Number(res.header['X-Pagination-Page-Count'])
      if (this.otfenStorePage >= totalPage) {
        this.canAddOtfenStore = false
      }
      if (otfenStore) {
        this.setState({
          otfenStore: [...otfenStore, ...data]
        })
      } else {
        this.setState({
          otfenStore: [...data]
        })
      }
    })
  }

  private addAllStoreStatus = false
  private allStorePage: number = 1
  async addAllStore(e) {
    if (!this.addAllStoreStatus) {
      this.allStorePage++
      this.addAllStoreStatus = true
      await this.getAllStore()
      this.addAllStoreStatus = false
    }
  }
  // 全部门店
  getAllStore(params?) {
    const { address } = params || this.state
    let paramsData = {
      userLongitude: address.location.lng,
      userLatitude: address.location.lat,
      query: {
        page: this.allStorePage
      }
    }
    // 如果链接携带分销信息 查询门店时需一起发送
    let { goodsDistributionId } = this.$instance.router.params
    if (goodsDistributionId) {
      paramsData.query.goodsDistributionId = goodsDistributionId
    }

    allStore(paramsData).then(res => {
      const data = res.data.data
      const { allStoreList } = this.state
      if (allStoreList.length) {
        this.setState({
          allStoreList: [...allStoreList, ...data]
        })
      } else {
        this.setState({
          allStoreList: [...data]
        })
      }
    })
  }
  // 全部门店界面
  allStoreView() {
    const { store, allStoreList } = this.state
    const { method } = this.$instance.router.params
    return (
      <ScrollView lowerThreshold={120} scrollY onScrollToLower={(e) => this.addAllStore(e)} className={classnames('otfen-store', method === 'vendorStore' && 'show')}>
        {
          store && (
            <View className='curr-store'>
              <View className='sub-title'>当前门店</View>
              <View className='store-item'>
                <StoreListView list={store} />
              </View>
            </View>
          )
        }
        {
          allStoreList.length > 0 && (
            <View className='otfen-list'>
              <View className='sub-title'>可用门店</View>
              {
                allStoreList.map(list => {
                  return <StoreListView handleEvent={this.changeStore.bind(this)} key={list.id} list={list} />
                })
              }
            </View>
          )
        }
      </ScrollView>
    )
  }

  // 搜索
  searchLocation = debounce((e) => {
		let { goodsDistributionId } = this.$instance.router.params
    const { value: keyword } = e.detail
		console.log('搜索',e)
		console.log('keyword',keyword)
    if (keyword) {
			this.setState({
				keyword
			})
      const { address } = this.state
			console.log('address',address)
			let paramsData = {}
			if(process.env.TARO_ENV === 'weapp'){
				paramsData = {
					userLongitude: address.location.lng,
					userLatitude: address.location.lat,
					// keyword,
					query: {
						page:1,filter:{or:[{storeNameKeyword:{klike:keyword}},{addressKeyword:{klike:keyword}}]},
						sort:"-createdAt",
						goodsDistributionId:goodsDistributionId || ''
					}
				}
			}else{
				paramsData = {
					userLongitude: address.longitude,
					userLatitude: address.latitude,
					// keyword,
					query: JSON.stringify({
						page:1,filter:{or:[{storeNameKeyword:{klike:keyword}},{addressKeyword:{klike:keyword}}]},
						sort:"-createdAt",
						goodsDistributionId:goodsDistributionId || ''
					})
				}
			}

			console.log('paramsData',paramsData)
      // 如果链接携带分销信息 查询门店时需一起发送
			// let { goodsDistributionId } = this.$instance.router.params
      // if (goodsDistributionId) {
      //   paramsData.query.goodsDistributionId = goodsDistributionId
      // }
      allStore(paramsData).then(res => {
        const data = res.data.data
        this.setState({
          keyWordStore: data
        })
      })
    } else {
      this.setState({
				keyword:'',
        keyWordStore: []
      })
    }
  }, 500)

	// 搜索
  searchScrollLocation = () => {
		let {keyword,keyWordStore} = this.state
    if (keyword) {
      const { address } = this.state
      let paramsData = {
        userLongitude: address.location.lng,
        userLatitude: address.location.lat,
        query: {
					page:this.searchStorePage,filter:{or:[{storeNameKeyword:{klike:keyword}},{addressKeyword:{klike:keyword}}]},
					sort:"-createdAt"
				}
      }
      // 如果链接携带分销信息 查询门店时需一起发送
      let { goodsDistributionId } = this.$instance.router.params
      if (goodsDistributionId) {
        paramsData.query.goodsDistributionId = goodsDistributionId
      }
      allStore(paramsData).then(res => {
        const data = res.data.data
				const totalPage = Number(res.header['x-pagination-page-count']) || Number(res.header['X-Pagination-Page-Count'])
        if (this.searchStorePage >= totalPage) {
          this.canSearchNearStore = false
        }
				if(keyWordStore){
					this.setState({
						keyWordStore: [...keyWordStore,...data]
					})
				}else{
					this.setState({
						keyWordStore:data
					})
				}

      })
    } else {
      this.setState({
        keyWordStore: []
      })
    }
  }

  async changeStore(store?) {
    console.log('store: ', store);
    store['topUrl'] = store['logo']
    const { dispatchStore } = this.props
    await dispatchStore(store)
    this.setState({
      store
    }, () => {
      const REDIRECT_PATH = Taro.getStorageSync('REDIRECT_PATH')
      if (REDIRECT_PATH) {
        Taro.removeStorageSync('REDIRECT_PATH')
        Taro.navigateTo({
          url: REDIRECT_PATH
        })
      } else {
        Taro.switchTab({ url: '/pages/tabbar/index/index' })
      }
    })
  }

  private addOtfenStoreStatus = false
  private otfenStorePage = 1
  private canAddOtfenStore: boolean = true
  async addOtfenStore(e) {
    // 暂禁止常用门店滚动加载（考虑到常用门店数据不会多）
    const disableScroll = true
    if (disableScroll) return
    if (!this.canAddOtfenStore) return
    if (!this.addOtfenStoreStatus) {
      this.otfenStorePage++
      this.addOtfenStoreStatus = true
      await this.getOtfenStore()
      this.addOtfenStoreStatus = false
    }
  }

	reloadLocation=()=>{
		// 切换城市
		Taro.setStorageSync('IS_RELOAD_STORE_INFO','1')
		let {isTopicAnnualCard=0} =  this.$instance.router.params
		Taro.navigateTo({
			url: `/pages/platform/city/index?type=1&isTopicAnnualCard=${isTopicAnnualCard}`
		})



		// this.nearStorePage = 1
		// this.setState({
		// 	isReload:true,
		// 	commonlyUsed:[],
		// 	nearStore:[],
		// },()=>{
		// 	this.getNearStore('init', true)
		// 	console.log('微信提示')
		// })
	}

  // 常用门店界面
  otfenStoreView() {
    const { store, otfenStore, tabIndex } = this.state
    return (
      <ScrollView lowerThreshold={120} scrollY onScrollToLower={(e) => this.addOtfenStore(e)} className={classnames('otfen-store', tabIndex === 1 && 'show')}>
        {
          otfenStore && otfenStore.length && (
            <View className='otfen-list'>
              <View className='sub-title'>常用门店</View>
              {
                otfenStore.map(list => {
                  return <StoreListView handleEvent={this.changeStore.bind(this)} key={list.id} list={list} />
                })
              }
            </View>
          )
        }
      </ScrollView>
    )
  }
  private canAddNearStore: boolean = true
  private addNearStoreStatus = false
  private nearStorePage = 1
  async addNearStore(e) {
    if (!this.canAddNearStore) return
    if (!this.addNearStoreStatus) {
      this.nearStorePage++
      this.addNearStoreStatus = true
      console.log(this.nearStorePage)
      await this.getNearStore()
      this.addNearStoreStatus = false
    }
  }
	// 搜索门店
	private canSearchNearStore: boolean = true
  private searchNearStoreStatus = false
  private searchStorePage = 1
  async searchNearStore(e) {
    if (!this.canSearchNearStore) return
    if (!this.searchNearStoreStatus) {
      this.searchStorePage++
      this.searchNearStoreStatus = true
      console.log(this.searchStorePage)
      await this.searchScrollLocation()
      this.searchNearStoreStatus = false
    }
  }
  // 附近门店界面
  nearStoreView() {
    const { address, reload, nearStore, commonlyUsed, tabIndex ,selectArea} = this.state
		let IS_RELOAD_STORE_INFO = Taro.getStorageSync('IS_RELOAD_STORE_INFO')
    return (
      <ScrollView lowerThreshold={120} scrollY onScrollToLower={(e) => {
        this.addNearStore(e)
      }} className={classnames('near-store', tabIndex === 2 && 'show')}
      >
        <View className='sub-title'>已选城市</View>
        {
          address ?
            <View className='current-location'>
              {
								<View className='location-info'>
									<View className='name'>{ IS_RELOAD_STORE_INFO && IS_RELOAD_STORE_INFO == 1 && selectArea.name ? selectArea.name : Taro.getStorageSync('CURRENT_LOCATION_INFO').name}</View>
								</View>
              }
              <AtButton onClick={this.reloadLocation} className='reset-location' size='small' loading={!reload} type='secondary'>
                 切换城市
              </AtButton>
            </View> :
            <View className='current-location'>
              <View className='location-info'><View className='name'>暂无位置信息</View></View>

            </View>
        }
        {
          nearStore && nearStore.length > 0 && (
            <View className='near-list'>
              {
                commonlyUsed && commonlyUsed.length > 0 &&
                <Fragment>
                  <View className='sub-title'>常用门店</View>
                  {
                    commonlyUsed.map(list => {
                      return <StoreListView handleEvent={this.changeStore.bind(this)} key={list.id} list={list} />
                    })
                  }
                </Fragment>
              }
              <View className='sub-title'>附近门店</View>
              {
                nearStore.map(list => {
                  return <StoreListView handleEvent={this.changeStore.bind(this)} key={list.id} list={list} />
                })
              }
            </View>
          )
        }
      </ScrollView>
    )
  }

  // 搜索门店界面
  keywordStoreView() {
    const { keyWordStore } = this.state
    return keyWordStore.length > 0 ? (
			<ScrollView className={classnames('keyword-store-content')} scrollY onScrollToLower={(e) => {
        this.searchNearStore(e)
      }} >
				{/*  */}
      <View >
        {
          keyWordStore.map(list => {
            return <StoreListView handleEvent={this.changeStore.bind(this)} key={list.id} list={list} />
          })
        }
      </View>
			</ScrollView>
    ) : null
  }
  getFun = () => {
    this.getNearStore()
  }
  render() {
    const { loadLocation, address,keyword } = this.state
    return loadLocation && (
      <View className='store-index'>
        {
          address ? (
            <View className={classnames('store-main')}>
              <View className='store-index-fixed'>
                <View className='import-keywords'>
									<Input value ={keyword} placeholder-class='placeholder' onInput={(e) => this.searchLocation(e)} className='ipt' placeholder='输入门店名称、地址或区域'></Input>
									</View>
							</View>
              {/* {method === 'vendorStore' ? this.allStoreView() : this.otfenStoreView()} */}
              {this.nearStoreView()}
              {this.keywordStoreView()}
            </View>
          ) : <OpenLocation getFun={this.getFun} />
        }
      </View>
    )
  }
}
